#include <stdio.h>
#include <pthread.h>
#include <unistd.h>


int yes_or_no =0;
pthread_mutex_t mutex ;
pthread_cond_t cond_cus;
pthread_cond_t cond_cook;

void* customer(void *arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    while(yes_or_no==0)
    {
      pthread_cond_wait(&cond_cus,&mutex );

    }
    yes_or_no=0;
    printf("饭真好吃，再来一碗！\n");
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond_cook);
  }
}
void* cook(void *arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    while(yes_or_no==1)
    {
      pthread_cond_wait(&cond_cook,&mutex );
    }
    yes_or_no=1;
    printf("你好，饭做好了！\n");
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond_cus);
  }

}
int main()
{
  int ret,i,j;
  pthread_t cus_tid[4],cook_tid[4];

  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond_cus,NULL);
  pthread_cond_init(&cond_cook,NULL);

  for(i=0;i<4;i++)
  {
  ret=pthread_create(&cus_tid[i],NULL,customer,NULL);
  if(ret!=0)
  {
    printf("pthread create error!\n");
    return -1;
  }


 ret=pthread_create(&cook_tid[i],NULL,cook,NULL);
 if(ret!=0)
 {
   printf("pthread create error!\n");
   return -1;
 }
  }

  for(j=0;j<4;j++)
  {
 pthread_join(cus_tid[j],NULL);
 pthread_join(cook_tid[j],NULL);
  }
 pthread_mutex_destroy(&mutex);
 pthread_cond_destroy(&cond_cus);
 pthread_cond_destroy(&cond_cook);
  return 0;
}
